# coding: utf-8
from me.api_utils import *
from me.api_utils import WXAppAPIView as APIView
from .model_serializers import *
from me.wxapi import *
from profiles.models import *


class UserLoginAPIView(APIView):
    permission_classes = ()
    authentication_classes = ()

    def post(self, request):
        code = request.data.get('code', '')
        user_info = request.data.get('info', None)
        session_info = exchange_code_for_session_key(code)
        # session_key = session_info.get('session_key')
        openid = session_info.get('openid')
        user_auth = UserAuth.get_or_create(openid, 'weixin')
        user = user_auth.user

        if user_info is not None:
            user = user_auth.user
            user_info = user_info.get('userInfo')
            user.nickname = user_info.get('nickName')
            user.gender = user_info.get('gender')
            user.avatar = user_info.get('avatarUrl')
            user.save()

        WXAppToken.update_token(user)

        return success_resp(UserWXAppSerializers(instance=user).data)

